package com.didispace.aspect;

import java.util.Arrays;

import javax.servlet.http.HttpServletRequest;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;


/**
 * WEB日志切面
 * @author wuyanzu
 * @version 1.0.0
 * @date 18/5/2 上午10:50.
 * @blog https://www.cnblogs.com/7motor28/
 */
@Aspect
@Order(5)
@Component
public class WebLogAspect {

    private Logger logger = LoggerFactory.getLogger(getClass());

    ThreadLocal<Long> startTime = new ThreadLocal<>();

    //环绕通知,环绕增强，相当于MethodInterceptor  
    @Around("@annotation(aopAccess)")
    public Object arround(ProceedingJoinPoint pjp, AopAccess aopAccess) throws Throwable {  
        // 接收到请求，记录请求内容
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        Object o =  pjp.proceed();
        logger.info("URL:::" + request.getRequestURL().toString() + "?" + request.getQueryString() +
			        "|HTTP_METHOD:::" + request.getMethod() +
			        "|IP:::" + request.getRemoteAddr() +
			        "|CLASS_METHOD:::" + pjp.getSignature().getDeclaringTypeName() + "." + pjp.getSignature().getName() +
			        "|ARGS:::" + Arrays.toString(pjp.getArgs()) +
			        "|DESC:::"+aopAccess.desc() +
                    "|RESPONSE:::" + o);
        if(o.toString().contains("Exception")){
        	Object[] args = pjp.getArgs();
        	Exception e = (Exception) args[1];
        	System.out.println(e.getMessage());
        }
        return o;  
    }

}

